﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Gueei.Gallery.Core.Repositories
{
	public class LocalFileRepository : IFileRepository
	{
		public LocalFileRepository(string localPath)
		{
			LocalPath = localPath;
			// Create directory if needed
			Directory.CreateDirectory(LocalPath);
		}

		protected string LocalPath
		{
			get;
			set;
		}

		private readonly int _bufferSize = 4096;
		public bool SaveFile(Guid id, byte[] content, bool overwrite)
		{

			// Do nothing as file exists
			if (FileExists(id) && !overwrite) return false;

			int current = 0;

			using (var fs = new BufferedStream(File.Create(GetFileFullPath(id))))
			{
				while (current < content.Length)
				{
					fs.Write(content, current,
						(current + _bufferSize > content.Length) ? content.Length - current : _bufferSize);
					current += _bufferSize;
				}
			}

			return true;
		}

		public bool FileExists(Guid id)
		{
			return File.Exists(GetFileFullPath(id));
		}

		public string GetFileFullPath(Guid id)
		{
			return Path.Combine(LocalPath, id.ToString());
		}

		public byte[] RetriveFile(Guid id)
		{
			if (!FileExists(id)) throw new ArgumentException("File not exists");
			byte[] data;
			int current = 0;
			using (var fs = File.OpenRead(GetFileFullPath(id)))
			{
				data = new byte[fs.Length];
				while(current<fs.Length)
				{
					fs.Read(data, current,
						(current + _bufferSize > fs.Length) ? (int)(fs.Length - current) : _bufferSize);
					current += _bufferSize;
				}
			}
			return data;
		}
	}
}
